package service

import (
	"context"
	"product-server/bsic/config"
	__ "product-server/bsic/proto"
	"product-server/handler/models"
	"strconv"
)

type Server struct {
	__.UnimplementedProductServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) ProductAdd(_ context.Context, in *__.ProductAddReq) (*__.ProductAddResp, error) {

	product := models.Product{
		ProductName: in.ProductName,
		Stock:       strconv.FormatInt(in.Stock, 10),
		Price:       in.Price,
		Image:       in.Image,
	}

	if err := product.ProductNameAdd(config.DB); err != nil {
		return nil, err
	}

	return &__.ProductAddResp{
		ProductId: int64(product.ID),
	}, nil
}

func (s *Server) ProductShow(_ context.Context, in *__.ProductShowReq) (*__.ProductShowResp, error) {

	var product models.Product
	if err := product.ProductNameShow(config.DB, in.ProductId); err != nil {
		return nil, err
	}

	return &__.ProductShowResp{
		ProductName: product.ProductName,
		Stock:       product.Stock,
		Price:       product.Price,
		Image:       product.Image,
	}, nil
}

func (s *Server) ProductDel(_ context.Context, in *__.ProductDelReq) (*__.ProductDelResp, error) {

	var product models.Product

	if err := product.ProductDel(config.DB, in.ProductId); err != nil {
		return nil, err
	}

	return &__.ProductDelResp{}, nil
}
func (s *Server) ProductUpdate(_ context.Context, in *__.ProductUpdateReq) (*__.ProductUpdateResp, error) {

	var product models.Product

	product = models.Product{
		ProductName: in.ProductName,
		Stock:       strconv.FormatInt(in.Stock, 10),
		Price:       in.Price,
		Image:       in.Image,
	}

	if err := product.ProductUpdate(config.DB); err != nil {
		return nil, err
	}

	return &__.ProductUpdateResp{
		ProductId: int64(product.ID),
	}, nil
}
func (s *Server) ProductList(_ context.Context, in *__.ProductListReq) (*__.ProductListResp, error) {

	var product models.Product

	var products []*__.ProductList

	list, err := product.ProductList(config.DB, products)
	if err != nil {
		return nil, err
	}

	return &__.ProductListResp{
		List: list,
	}, nil
}
